<template>
    <div>
        <el-form :inline="true" class="demo-form-inline" v-model="search" label-position="right">
            <el-form-item label="机型">
                 <el-select v-model="search.macType" placeholder="请选择机型">
                    <el-option
                    v-for="item in allMachine"
                    :key="item.id"
                    :label="item.type"
                    :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="机器台数">
                <el-input v-model="search.macNums" class="inputSuffix">
                    <template slot="append">台</template>
                </el-input>
            </el-form-item>
            <el-form-item label="生产人数">
                <el-input v-model="search.persons" class="inputSuffix">
                     <template slot="append">人</template>
                </el-input>
            </el-form-item>
             <el-form-item label="生产结束时间">
                <el-date-picker
                    v-model="search.startTime"
                    type="date"
                    placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
            <el-button type="primary" @click="openCharts">查询</el-button>
            <el-button type="warning" plain @click="createCgPlan">生成计划</el-button>
        </el-form>
        <el-form :inline="true" class="demo-form-inline" v-model="planTime" label-position="right" v-if="planTime.producteStartTime!=''">
             <el-form-item label="生产开始时间">
                <el-date-picker
                    v-model="planTime.producteStartTime"
                    type="date"
                    placeholder="选择日期" disabled>
                </el-date-picker>
            </el-form-item>
            <el-form-item label="生产耗时">
                <el-input v-model="planTime.useTime" class="inputSuffix" disabled>
                     <template slot="append">天</template>
                </el-input>
            </el-form-item>
             <el-form-item label="采购价格">
                <el-input v-model="planTime.totolPrice" class="inputSuffix" disabled>
                     <template slot="append">元</template>
                </el-input>
            </el-form-item>
        </el-form>
        <div id='chart' ref='chart' :style="{height:tableHeight+'px'}"></div>
    </div>
</template>
<script>
import echarts from 'echarts';
import planHttp from '@/axios/planProduct.js'
import scybHttp from '@/axios/scybHttp.js'
import cgbHttp from '@/axios/cgbHttp.js'
export default {
    data(){
        return{
            payTypeList:[],/**付款方式 */
            search:{
                macNums:'',
                persons:'',
                macType:'',
                startTime:''
            },
            planTime:{
                producteStartTime:'',
                useTime:'',
                totolPrice:''
            },
            chartCustom:null,
            tableHeight: document.documentElement.clientHeight - 170,/**表格高度 */
            allMachine:[],
        }
    },
    created(){
        let self= this;;
        /**获取所有机型 */

        cgbHttp.supplierCode(6).then(res=>{
             /**获取付款方式 */
            self.payTypeList = res.content;
        })
        self.getAllMachine();
    },
    mounted(){
        let self = this;
    },
    methods:{
        openCharts(){
            this.getPlanData();
        },
        getAllMachine(){/**获取所有机型 */
            let self = this;
            scybHttp.bzAllJy().then(res=>{
                self.allMachine = res.content;
            })
        },
        getPlanData(){
           let self = this;
           const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
           let yAxis = {type:'category',data:[]};
           let purchases=[],product = [],payPlan=[];

           let xAxis ={type: 'time',splitNumber:20,axisLabel:{
               rotate:30,
               formatter(value, index){
                    var date = new Date(value);
                    let year = date.getFullYear();
                    let month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
                    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
                    let hours = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
                    let minutes = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
                    let seconds = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
                    return `${month}-${D} ${hours}:${minutes}:${seconds}`
               }
           }};
            let series=[];
            self.chartCustom = echarts.init(self.$refs.chart);
            self.search.startTime = self.timestampToTime1(self.search.startTime,'yy-mm-dd hh:mm:ss');
            self.search.cgType = 1;
           planHttp.getPlanData(self.search).then(res=>{
                self.planTime.totolPrice = res.content.total;
                self.planTime.producteStartTime=res.content.result[res.content.result.length-1].startTime;
                self.planTime.useTime =((new Date(res.content.result[0].endTime).getTime() -new Date(res.content.result[res.content.result.length-1].startTime).getTime())/(3600*1000*24)).toFixed(2)
                res.content.result.forEach((element,j) => {
                   let flag= true;
                   let startArray= [element.startTime,element.name,element.useTime];
                   let endArray=[element.endTime,element.name];
                   let lateDate = new Date(new Date(element.lateDate).getTime() + 3600*1000*24);
                 product.push({
                     type:'custom',
                     name:'生产计划',
                     encode: {x: [1, 2], y:0},
                     renderItem:self.renderItem,
                     itemStyle: {
                            normal: {
                                color: 'rgba(64,158,255,0.8)'
                            }
                        },
                     data:[
                         {
                            name:element.name,
                            value: [
                                element.name,
                                element.startTime,
                                element.endTime,
                                element.useTime,
                                element.deTime
                            ]
                         }
                     ]
                 })

                   if(yAxis.data.length>0){
                       for(let i=0;i< yAxis.data.length;i++){
                           if(element.name===yAxis.data[i]){
                               flag = false;
                               if(purchases[purchases.length-1].name==='采购计划'){
                                  purchases[purchases.length-1].data[0].value[2] = (new Date(purchases[purchases.length-1].data[0].value[2]).getTime())-(new Date(element.startTime).getTime())>0?element.startTime:purchases[purchases.length-1].data[0].value[2];
                               }
                               return
                           }
                       }
                        if(flag){
                            yAxis.data.push(element.name);
                            if(element.preDate){
                                purchases.push({
                                    type:'custom',
                                    name:'采购计划',
                                    encode: {x: [1, 2], y:0},
                                    renderItem:self.renderItem,
                                    itemStyle: {
                                        normal: {
                                            color: 'rgba(230,162,60,0.8)'
                                        }
                                    },
                                    data:[
                                        {
                                        name:element.name,
                                        value: [
                                            element.name,
                                            element.preDate,
                                            element.arriveDate,
                                            Number((new Date(element.arriveDate).getTime()- new Date(element.preDate).getTime())/(3600*1000*24)).toFixed(1)+"天",
                                            element.cgMaterials
                                        ]
                                        }
                                    ]
                                })
                            }
                            if(element.earlyDate){
                                payPlan.push({
                                    type:'custom',
                                    name:'付款计划',
                                    encode: {x: [1, 2], y:0},
                                    renderItem:self.renderItem,
                                    itemStyle: {
                                        normal: {
                                            color: 'rgba(114,26,204,0.8)'
                                        }
                                    },
                                    data:[
                                        {
                                        name:element.name,
                                        value: [
                                            element.name,
                                            element.earlyDate,
                                            lateDate,
                                            Number((new Date(lateDate).getTime()- new Date(element.earlyDate).getTime())/(3600*1000*24)).toFixed(1)+"天",
                                            element.cgMaterials
                                        ]
                                        }
                                    ]
                                })
                            }
                        }
                    }else{
                        yAxis.data.push(element.name);
                        if(element.preDate){
                            purchases.push({
                                type:'custom',
                                name:'采购计划',
                                encode: {x: [1, 2], y:0},
                                renderItem:self.renderItem,
                                itemStyle: {
                                    normal: {
                                        color: '#e6a23c'
                                    }
                                },
                                data:[
                                    {
                                    name:element.name,
                                    value: [
                                        element.name,
                                        element.preDate,
                                        element.arriveDate,
                                        Number((new Date(element.arriveDate).getTime()- new Date(element.preDate).getTime())/(3600*1000*24)).toFixed(1)+"天",
                                        element.cgMaterials
                                    ]
                                    }
                                ]
                            })
                        }
                        if(element.earlyDate){
                                payPlan.push({
                                    type:'custom',
                                    name:'付款计划',
                                    encode: {x: [1, 2], y:0},
                                    renderItem:self.renderItem,
                                    itemStyle: {
                                        normal: {
                                            color: 'rgba(114,26,204,0.8)'
                                        }
                                    },
                                    data:[
                                        {
                                        name:element.name,
                                        value: [
                                            element.name,
                                            element.earlyDate,
                                            lateDate,
                                            Number((new Date(lateDate).getTime()- new Date(element.earlyDate).getTime())/(3600*1000*24)).toFixed(1)+"天",
                                            element.cgMaterials
                                        ]
                                        }
                                    ]
                                })
                            }
                    }
               });
                series = purchases.concat(product,payPlan);
                self.chartCustom.clear();
                self.chartCustom.setOption({
                    title: {
                    text: '生产计划',
                    },
                    tooltip: {
                        enterable:true,
                         position: function (pos, params, dom, rect, size) {
                              // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
                            var obj = {top: 60};
                            obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
                            return obj;
                        },
                        formatter: function (params) {
                              if(params.seriesName==='生产计划'){
                                   return params.value[0]+ '<br/>' +'开始时间：'+ params.value[1]+ '<br/>' +'结束时间：'+ params.value[2]+ '<br/>'+'耗时：'+ params.value[3]+"分钟"+'<br/>定额：'+params.value[4]+'分钟';
                              }else{
                                  let content='<table class="bomTable"><thead><tr><th class="name">bom名称</th><th>单价</th><th>购买量</th><th class="startTime">采购开始时间</th><th class="time">采购提前期</th><th class="payWay">付款方式</th><th class="timeSort">付款时间</th><th class="timeSort">总价</th><th class="timeSort">供应商</th></tr></thead><tbody>';
                                    let bomList = params.value[4].sort((a,b)=>{
                                        return   new Date(a.preDate).getTime()-new Date(b.preDate).getTime()
                                    })
                                    bomList.forEach(item=>{
                                        if(item.isNeedBuy===1&&item.preDate){
                                            let payWay =''
                                            if(item.payMethod){
                                                self.payTypeList.forEach(el=>{
                                                    if(item.payMethod === el.code){
                                                        payWay= el.name;
                                                    }
                                                })
                                            }

                                            content+=`<tr><td>${item.name}</td><td>￥${item.price}</td><td>${item.actNums}</td><td>${item.preDate}</td><td>${item.cgBomSupplier.predate}天</td><td>${payWay}</td><td>${item.latePayDate}</td><td>￥${item.totals}</td><td>${item.cgSupplier.name}</td></tr>`
                                        }
                                    })
                                    return params.value[0] +'<br/>'+content+'</tbody></table>';
                              }
                        }
                    },
                    legend: {
                    data: ['采购计划', '生产计划','付款计划']
                    },
                    grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                    },
                    yAxis:yAxis,
                    xAxis: xAxis,
                    series: series
                })
                 loading.close();
           },error=>{
                loading.close();
           })
        },
        renderItem(params, api) {
            let categoryIndex = api.value(0);
            let start = api.coord([api.value(1), categoryIndex]);
            let end = api.coord([api.value(2), categoryIndex]);
            let height = api.size([0, 1])[1] * 0.6;

            let rectShape = echarts.graphic.clipRectByRect({
                x: start[0],
                y: start[1] - height / 2,
                width: end[0] - start[0],
                height: height
            }, {
                x: params.coordSys.x,
                y: params.coordSys.y,
                width: params.coordSys.width,
                height: params.coordSys.height
            });

            return rectShape && {
                type: 'rect',
                shape: rectShape,
                style: api.style()
            };
        },
        createCgPlan(){
            let self = this;
             self.$confirm('是否生成机器采购计划?', '提示', {
            confirmButtonClass: 'el-button--warning'
            }).then(() => {
                const loading = this.$loading({
                    lock: true,
                    text: '正在生产计划...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                let postData={
                    macNums: self.search.macNums,
                    persons:self.search.persons,
                    startTime: self.timestampToTime1(self.search.startTime,'yy-mm-dd hh:mm:ss'),
                    macType:self.search.macType,
                    cgType:self.search.cgType
                }
                planHttp.createCgPlan(postData).then(res=>{
                    loading.close();
                     this.$confirm(`机器采购计划生成成功,令号：<span style="color:#67C23A;font-size:16px;">${res.content}</span>`, '提示', {
                        confirmButtonText: '确定',
                        type: 'success',
                        dangerouslyUseHTMLString:true,
                        center: true,
                        showCancelButton:false
                        })
                },error=>{
                    loading.close();
                    self.$message.error(`采购计划生成失败`);
                })
            }).catch(() => {})
        }
    }
}
</script>
<style>
.bomTable{
    line-height: 24px;
    text-align: center;
}
.bomTable .name ,.bomTable .payWay{
    width:100px;
}
.bomTable .startTime,.bomTable .timeSort{
    width:100px;
}
.bomTable .time{
    width:100px;
}
.bomTable tb{
    position: relative;
}
.bomTable .toolbar{
    height:24px;
    background: #e6a23c;
    color:#fff;
    display: inline-block;
    float:right;
}
</style>


